package com.os.ordersystem.controller;

import com.os.ordersystem.bean.ResultDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;


//图片上传
@RestController
@CrossOrigin
@RequestMapping("/upload")
public class FileUploadController {

    @Value("${uploadImgPath}")
    private String uploadImgPath;

    @PostMapping("/imgUpload")
    public ResultDTO fileUpload(MultipartFile file, HttpServletRequest request){

            File dir = new File(uploadImgPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            System.out.println("uploadImgPath："+ uploadImgPath);

            //文件名
            String fileName = file.getOriginalFilename();
            System.out.println("fileName："+ fileName);

            //文件后缀
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("suffixName："+ suffixName);

            //uuid
            fileName = UUID.randomUUID().toString().replace("-", "") + suffixName;
        System.out.println("fileName："+ fileName);

            File newFile = new File(uploadImgPath + fileName);

            try {
                file.transferTo(newFile);
                return ResultDTO.success(fileName);
            } catch (IOException e) {
                e.printStackTrace();
                return ResultDTO.erro();
            }

    }
}
